<template>
  <div class="memberManage" id="memberManage">
    <!-- 功能按钮 -->
    <div class="numberManage_button">
      <a-button class="addButton" type="primary" 
      :disabled="creatAble"
      @click="addRecord">
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        添加成员
      </a-button>
    </div>
    <!-- 表格展示部分 -->
    <baseTable :columns="columns.memberManagesColumns" :dataSource="configData.records" :isSelect="true" :scroll="scroll"
      ref="memeberBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
      :total="configData.total" @changePage="changePage">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'isEnabled'">
          <a-switch @click="switchChange(record)" size="small" v-model:checked="record.isEnabled" />
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a-popconfirm placement="topRight" v-if="!isOrgVisible" ok-text="移除" cancel-text="取消"
            @confirm="deleteRecords([record.id])">
            <template #title>
              <p style="width: 197px">
                {{ `是否将该用户【'${record.userName}】从虚拟组织【${record.orgName}】中移除？` }}
              </p>
            </template>
          </a-popconfirm>
          <a :class="{ disable: deleteAble }" @click="removeMember(record)">{{
            record.oparation[0] }}</a>
        </template>
      </template>
      <template #otherOpration>
        <a-button :style="{ 'margin-left': '8px' }" 
        @click="moveSelectedAll"
          :disabled="!memberrowSelection.length || deleteAble">移除</a-button></template>
    </baseTable>
    <!-- 添加成员模态框 -->

    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="isVisible = false" class="addMember_modal">
      <template v-slot:body>
        <div class="modal_table">
          <div class="table-header">
            <p class="org-text">所属组织：</p>
            <a-select class="modal-select" v-model:value="formState.upOrg.value" mode="multiple" @change="changeMember"
              placeholder="请选择" optionFilterProp="label" show-search showArrow
              :options="upOrgOptions.map((item: any) => ({ label: item.name, value: item.id, disabled: item.disabled }))"></a-select>
            <div class="searchContent">
              <a-input v-model:value="searchName" placeholder="搜索用户名或真实姓名" style="width: 192px">
                <template #suffix>
                  <i class="iconfont icon-search" @click="onSearch"></i>
                </template>
              </a-input>
            </div>
          </div>
          <!-- 添加成员表格展示部分 -->
          <div class="baseTable">
            <baseTable :columns="columns.addMemberColumns" :dataSource="addmemberData.records" :isSelect="true"
              :scroll="{ y: 200 }" ref="addmemeberBaseTables" :isShowPagination="isShowPagination"
              :showCheckDelete="showCheckDelete" :total="addmemberData.total" @changePage="changePageOrg">
            </baseTable>
          </div>
        </div>

      </template>
    </base-modal>
    <!--移除成员模态框 -->
    <base-modal :width="modAlOrgProps.width" :isVisible="isOrgVisible" :title="modAlOrgProps.title" :buttons="orgbuttons"
      @handleOk="buttonOrgMessage" @handleCancle="isOrgVisible = false" class="org_modal">
      <template v-slot:body>
        <div class="model-content">
          {{ `是否将用户${isMoveAll ? '' : '【' + moverecord.userName +
            '】'}从【${moverecord.orgName}】中移除？该用户必须所属一个组织，请选择移除后归属的组织`
          }}
          <a-form name="advanced_search" autoComplete="off" class="ant-advanced-search-form" :model="formState"
            ref="contentFrom">
            <a-form-item class="form-select-item" :label="formState.upOrgMove.label" :name="['upOrgMove', 'value']"
              :rules="[formState.upOrgMove.rule]">
              <a-select v-model="formState.upOrgMove.value" @change="changeMove" placeholder="请选择"
                :options="upOrgOptions"></a-select>
            </a-form-item>
          </a-form>
        </div>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick, createVNode } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import baseModal from "@/components/modal/baseModal.vue";
import { useRoute } from 'vue-router'
import msgModal from "@/components/modal/modelConfig/MsGModal"
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { scrollType, modeProp } from "@/type.d";
import qs from 'qs';
import { keys } from "lodash";
import { Item } from "@antv/g6";
import {routerPerm} from '@/utils/common';
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}
//data
const creatAble = ref<boolean>(false);
const deleteAble = ref<boolean>(false);
const { query } = useRoute();
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true;  // 是否需要分页器中的自定义全选和删除
//表格数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
let addmemberData = reactive<configDataType>({ total: 0, size: 10, records: [] });
const memeberBaseTables = ref<any>(null); // basetable的ref
const addmemeberBaseTables = ref<any>(null); // 添加成员basetable的ref
let memberrowSelection = ref<(string | number)[]>([]);
let addmemberrowSelection = ref<(string | number)[]>([]);
let orgType = ref(Number(query.orgType))
const searchName = ref<string>('')

// 模态框数
const isVisible = ref<boolean>(false);//判断是否展示添加弹窗
const isOrgVisible = ref<boolean>(false);//判断是否展示移除弹窗
const isMoveAll = ref<boolean>(false); //判断是否是批量移除
const upOrgOptions = ref<dataSourceType[]>([])//选择组织的选项
const moverecord = ref<dataSourceType>({}) //移除的对应项数据展示
const modAlProps: modeProp = reactive({//添加成员modal选项
  width: "L",
  title: "添加成员",
});
const modAlOrgProps: modeProp = reactive({//移除成员modal选项
  width: "S",
  title: "移除成员",
});

const formState = reactive<dataSourceType>({
  upOrg: {
    value: [],
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "组织不可为空！",
    },
    label: "选择组织",
  },
  upOrgMove: {
    value: "",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "组织不可为空！",
    },
    label: "选择组织",
  },
  id: '',
  orgId: '',
  parentId: ''
});
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
const orgbuttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
// computed
memberrowSelection = computed(() => {
  return memeberBaseTables.value.selectedRowKeys
})
addmemberrowSelection = computed(() => {
  return addmemeberBaseTables.value.selectedRowKeys
})
//methods
const addRecord = async () => {//添加成员数据
  let datas = {
    pageNumber: 0,
    pageSize: 10,
  }
  geUserorgs();
  fetchMemberAdduserPage(datas)

};

const fetchMemberAdduserPage = async (datas: dataSourceType = {}) => {
  const data: {} = {
    pageNumber: datas.pageNumber || 0,
    pageSize: datas.pageSize || 10,
    excludeOrgId: query.id,
    name: datas.name || '',
    orgIds: formState.upOrg.value,

  };
  isVisible.value = true;
  modAlProps.title = "添加成员";
  buttons.value = [
    {
      text: "确定",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  const memberData = (await request.fetchMemberAdduserPage(data)) || {};
  let reqData = memberData;
  let sourceData = reactive<dataSourceType>({});
  const records: any[] = [];
  nextTick(() => {
    reqData?.records?.map((item: any, index: number) => {
      sourceData = {
        realName: item.realName,
        orgName: item.orgName,
        userName: item.userName,
        orgId: item.orgId,
        id: item.id,
      };
      records.push(sourceData);
    });
    addmemberData.total = reqData.total;
    addmemberData.size = reqData.size;
    addmemberData.records = records;
  })


}

const removeMember = (record: dataSourceType) => { //控制打开关
  if(deleteAble.value) return
  moverecord.value = record
  if (orgType.value === 1) {
    orgbuttons.value = [
      {
        text: "移除",
        "html-type": "submit",
        keepAlive: true,
      },
    ];
    isOrgVisible.value = true
    isMoveAll.value = false
  } else {
    deleteRecords([record.id])
  }
}

const onSearch = () => {//搜索用户名或真实姓名
  let datas: dataSourceType = {
    name: searchName.value
  }
  fetchMemberAdduserPage(datas);
}

const switchChange = async (record: dataSourceType) => { //开启关闭启用
  request[record.isEnabled ? 'fetchMemberEnable' : 'fetchMemberDisable']({ ids: [record.id] }).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
    } else {
      message.error(res.message);
    }
  })
    .catch((err: any) => {
      throw new Error(err);
    });
}

const changeMember = (e: string, options: any) => {//获取添加上级组织id
  nextTick(() => {
    fetchMemberAdduserPage();
  })
}
const changeMove = (e: string, options: any) => {//获取移除上级组织id
  formState.upOrgMove.value = e
  formState.parentId = options.id
}


const buttonOrgMessage = () => { //移除普通组织调用接口
  let keys: (string | number)[]
  if (isMoveAll.value) {
    keys = memberrowSelection.value;
  } else {
    keys = [moverecord.value.id]
  }

  if (!formState.upOrgMove.value) {
    message.warn('请选择组织！')
    return
  }
  deleteRecords(keys)
}

const buttonMessage = async (msg: dataSourceType) => {// 添加成员调取接口
  //保存

  let params: dataSourceType = {
    orgId: query.id,
    userIds: addmemberrowSelection.value
  };
  request.fetchOrganizeAdduser(params)
    .then((res: any) => {
      if (res.code == "00000 00000") {

        getRdecord();
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
  isVisible.value = msg.text == "确定" ? false : true;

};



const moveSelectedAll = async () => {//删除已选所有成员
  moverecord.value = configData.records[0]
  if (orgType.value === 1) {
    orgbuttons.value = [
      {
        text: "移除",
        "html-type": "submit",
        keepAlive: true,
      },
    ];
    isOrgVisible.value = true
    isMoveAll.value = true
    return
  }
  let keys: (string | number)[] = memberrowSelection.value;
  Modal.confirm(Object.assign({}, msgModal.confirm, {
    title: `是否将选中的用户从虚拟组织【${configData.records[0].orgName}】中移除？`,
    icon: createVNode("i", { class: "iconfont icon-warn warning_ICON", style: { 'font-size': '20px', 'color': '#FAAD14FF', 'position': 'absolute', 'top': '-4px' } }),
    okText: '移除',
    content: '',
    onOk: async () => {
      await deleteRecords(keys);
      Modal.destroyAll();
    },
    onCancel() {
      Modal.destroyAll();
    },
  },))
}
const deleteRecords = async (keys: (string | number)[] = []) => { // 调接口删除成员
  let params = {
    sourceOrgId: query.id,
    targetOrgId: orgType.value === 1 ? formState.parentId : 0,
    userIds: keys
  }
  await request.fetchOrganizeRemoveuser(params).then((res: any) => {
    if (res.code == "00000 00000") {
      getRdecord({});
      message.success(res.message);
      isOrgVisible.value = false
    } else {
      isOrgVisible.value = false
      message.error(res.message);
    }
  });
}

const getRdecord = async (datas: dataSourceType = {}) => { // 获取表格数据
  const data: {} = {
    pageNumber: datas.pageNumber || 0,
    pageSize: datas.pageSize || 10,
    orgId: query.id,
  };
  const telData = (await request.fetchMemberOrguserPage(data)) || {};
  let reqData = telData;
  let sourceData = reactive<dataSourceType>({});
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    sourceData = {
      oparation: ["移除"],
      userName: item.userName,
      orgName: item.orgName,
      realName: item.realName,
      userPhone: item.userPhone,
      userEmail: item.userEmail,
      isEnabled: item.isEnabled,
      orgId: item.orgId,
      id: item.id,
    };
    records.push(sourceData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;
  configData.records = records;
  nextTick(() => {
    scroll.y = getTableScroll(74, "memberManage").y;
    scroll.isFixed = getTableScroll(74, "memberManage").isFixed;
  })
};

//切换成员列表分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  let datas: dataSourceType = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize
  }
  getRdecord(datas);
}
//切换添加成员分页器
const changePageOrg = (data: { pageCurrent: any; pageSize: any }) => {
  let datas: dataSourceType = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize
  }
  fetchMemberAdduserPage(datas);
}

//获取当前用户可见组织列表
const geUserorgs = async () => { // 获取表格数据
  const data = (await request.fetchOrganizeUserorgs({ isIncludeVirOrg: true }));
  let reqData = data;
  reqData.forEach((item: any) => {
    item.value = item.name;
    if (item.id === Number(query.id)) {
      item.disabled = true
    } else {
      item.disabled = false
    }
  })
  upOrgOptions.value = reqData;
};
//onmounted
onMounted(() => {
  routerPerm().includes('creatAble') ? creatAble.value = false : creatAble.value = true;
  routerPerm().includes('deleteAble') ? deleteAble.value = false : deleteAble.value = true;
  geUserorgs();
  getRdecord();
});
</script>
<style lang="scss" scoped>
.memberManage {
  width: 100%;
  height: calc(100% - 84px);
  padding: 24px;
  background-color: #fff;
  overflow: hidden;

  .numberManage_button {
    padding-bottom: 24px;
    display: flex;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

  }

  .remove-link {
    color: rgba(0, 0, 0, 0.25);
  }

  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }
}
.disable {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}
.baseTable {
  position: relative;
}

.baseTable .aTable {
  max-height: 450px;
  height: fit-content;
  overflow: auto;
}

.table-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding-bottom: 24px;

  .org-text {
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
    line-height: 14px;
  }
}

.modal-select {
  width: 288px;
}

.ant-advanced-search-form {
  margin-top: 12px;
}

.searchContent {
  margin-left: 8px;

  .icon-search {
    font-size: 20px;
    color: rgba(0, 0, 0, 0.45);
    position: absolute;
    right: 12px;
    top: 0px;
  }
}

.tag-item {
  margin-bottom: 0 !important;
}

.form-select-item {
  font-size: 14px;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #FF4D4F;
}

::v-deep(.ant-table-tbody > tr > td:nth-last-of-type(1)) {
  text-align: right;
}

:deep(.ant-form-item:nth-last-of-type(1)) {
  margin-left: 0px;
}

::v-deep(.ant-input-affix-wrapper) {
  width: 514px;
  margin-left: 4px;
}
</style>
<style lang="scss">
.addMember_modal {
  .modal_table {
    height: 100%;
    overflow: hidden;
  }
}
</style>
